package com.yizhuoyan.his.serviceimpl.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yizhuoyan.his.ao.ModifyRoleAo;
import com.yizhuoyan.his.ao.RoleAddAo;
import com.yizhuoyan.his.dao.SysRoleDao;
import com.yizhuoyan.his.dto.QueryResult;
import com.yizhuoyan.his.entity.SysRoleEntity;
import com.yizhuoyan.his.exception.HISDataExistsException;
import com.yizhuoyan.his.service.admin.SysRoleManageService;
import com.yizhuoyan.his.servicesupport.DatabaseIdGenerateSupportService;
import com.yizhuoyan.his.util.BeanMap;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 角色管理
 */
@Transactional
@Validated
@Service
@Slf4j
public class SysRoleManageServiceImpl implements SysRoleManageService {
    @Autowired
    SysRoleDao sysRoleDao;
    @Autowired
    DatabaseIdGenerateSupportService databaseIdGenerateSupportService;

    @Override
    public SysRoleEntity addNewRole(@NonNull RoleAddAo ao) throws Exception {
        // 1验证参数
        log.trace("添加用户基本信息,参数为：{}", ao);
        String name = ao.getName();
        String code = ao.getCode();
        String remark = ao.getRemark();
        //1.1角色名称和代号不能重复
        if (sysRoleDao.exists("name", name) ||
                sysRoleDao.exists("code", code)) {
            log.trace("角色{}已存在，不可以添加", name);
            throw new HISDataExistsException(String.format("角色[%s]已存在", name));
        }
        log.trace("角色{}不存在，可以添加", name);
        // 2业务逻辑
        SysRoleEntity e = new SysRoleEntity();
        e.setId(databaseIdGenerateSupportService.nextId());
        e.setName(ao.getName());
        e.setCode(ao.getCode());
        e.setRemark(ao.getRemark());
        sysRoleDao.insert(e);
        log.trace("添加角色基本信息成功,参数为：{}", ao);
        return  e;
    }

    @Override
    public void modifyRole(@NonNull Long id, ModifyRoleAo ao) throws Exception {
        // 1验证参数
        if (!sysRoleDao.exists("id", id)) {
            log.trace("角色{}不存在，不可以修改", id);
            throw new HISDataExistsException(String.format("角色[%s]不存在", id));
        }
        // 2业务逻辑
        BeanMap updateMap = BeanMap.of(4);
        SysRoleEntity e = sysRoleDao.selectById(id);
        //修改code
        String newCode = ao.getCode();
        if (!Objects.equals(newCode, e.getCode())) {
            if (!sysRoleDao.exists("code", newCode)) {
                updateMap.append("code", newCode);
            } else {
                throw new HISDataExistsException(String.format("角色名称[%s]已存在", newCode));
            }
        }
        //修改name
        String newName = ao.getName();
        if (!Objects.equals(newName, e.getName())) {
            if (!sysRoleDao.exists("name", newName)) {
                updateMap.append("name", newName);
            } else {
                throw new HISDataExistsException(String.format("角色代号[%s]已存在", newName));
            }
        }
        //修改remark
        String newRemark = ao.getRemark();
        if (!Objects.equals(newName, e.getName())) {
            updateMap.append("remark", newRemark);
        }
        // 修改
        if (!updateMap.isEmpty()) {
            log.trace("执行更新，需要修改字段为{}", updateMap);
            sysRoleDao.update(id, updateMap);
        }
    }

    @Override
    public void removeRole(@NonNull Long id) throws Exception {
        // 1验证参数
        if (!sysRoleDao.exists("id", id)) {
            throw new Exception("查询id不存在");
        }
        // 2业务逻辑
        sysRoleDao.delete(id);
    }

    @Override
    public SysRoleEntity queryRole(Long id) throws Exception {
        SysRoleEntity e = sysRoleDao.selectById(id);
        return e;
    }

    @Override
    public QueryResult<SysRoleEntity> queryAllRoleByKey(String key, int pageNo, int pageSize) throws Exception {
        // 1验证参数
        if ((key == null) || ((key = key.trim()).length() == 0)) {
            key = "id";
        }
        if (pageNo <= 0) {
            pageNo = 1;
        }
        if (pageSize <= 0) {
            pageSize = 5;
        }
        // 2业务逻辑
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<SysRoleEntity> page = new PageInfo<>(sysRoleDao.selectAll(key));
        // 3 组装结果
        QueryResult<SysRoleEntity> result = new QueryResult<SysRoleEntity>();
        result.setPageNo(pageNo);
        result.setRows(page.getList());
        result.setTotalRows(page.getTotal());
        result.setPageSize(pageSize);
        return result;
    }
}
